package com.infoholdcity.common.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.infoholdcity.common.common.QueryConditionsDetailsVo;
import com.infoholdcity.common.common.QueryConditionsReqVo;
import com.infoholdcity.common.common.Result;
import com.infoholdcity.common.entity.QueryConditionsData;
import com.infoholdcity.common.entity.QueryConditionsMain;
import com.infoholdcity.common.service.QueryConditionsDataService;
import com.infoholdcity.common.service.QueryConditionsMainService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 * 查询条件主表 前端控制器
 * </p>
 *
 * @author jinshihui
 * @since 2025-02-20
 */
@RestController
@RequestMapping("/queryConditions")
@Slf4j
public class QueryConditionsMainController {

    @Autowired
    private QueryConditionsMainService queryConditionsMainService;

    @Autowired
    private QueryConditionsDataService queryConditionsDataService;

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 查询保存的条件
     * @param request
     * @return Result<Object>
     */
    @GetMapping(value = "/list")
    public Result<Object> list(HttpServletRequest request) throws JsonProcessingException {
        String username = request.getHeader("username");
        log.info("username的值：{}", username);
        //根据username查询query_conditions_main表的数据
        LambdaQueryWrapper<QueryConditionsMain> eq = Wrappers.lambdaQuery(QueryConditionsMain.class).eq(QueryConditionsMain::getUsername, username);
        List<QueryConditionsMain> queryConditionsMainList = queryConditionsMainService.list(eq);
        if(CollUtil.isEmpty(queryConditionsMainList)){
            return Result.ok("没有保存查询条件");
        }
        List<QueryConditionsDetailsVo> queryConditionsDetailsVoList = new ArrayList<>();
        QueryConditionsDetailsVo queryConditionsDetailsVo = null;
        for (QueryConditionsMain queryConditionsMain : queryConditionsMainList){
            queryConditionsDetailsVo = new QueryConditionsDetailsVo();
            String id = queryConditionsMain.getId();
            String saveName = queryConditionsMain.getSaveName();
            String matchType = queryConditionsMain.getMatchType();
            queryConditionsDetailsVo.setId(id);
            queryConditionsDetailsVo.setSaveName(saveName);
            queryConditionsDetailsVo.setMatchType(matchType);

            List<QueryConditionsData> queryConditionsDataList = queryConditionsDataService.list(Wrappers.lambdaQuery(QueryConditionsData.class).eq(QueryConditionsData::getMainId, queryConditionsMain.getId()));
            for (QueryConditionsData queryConditionsData : queryConditionsDataList){
                //json字符串
                String optionsJson  = queryConditionsData.getOptionss();
                if(StrUtil.isNotBlank(optionsJson)){
                    List<QueryConditionsData.Option> optionsBeans = objectMapper.readValue(optionsJson, new TypeReference<List<QueryConditionsData.Option>>() {});
                    queryConditionsData.setOptions(optionsBeans);
                }
            }
            queryConditionsDetailsVo.setData(queryConditionsDataList);
            queryConditionsDetailsVoList.add(queryConditionsDetailsVo);
        }
        return Result.ok(queryConditionsDetailsVoList);
    }

    @GetMapping(value = "/{id}")
    public ResponseEntity<QueryConditionsMain> getById(@PathVariable("id") String id) {
        return new ResponseEntity<>(queryConditionsMainService.getById(id), HttpStatus.OK);
    }

    /**
     *保存查询条件
     * @param queryConditionsReqVo
     * @return Result<Object>
     */
    @PostMapping(value = "/create")
    public Result<Object> create(@RequestBody QueryConditionsReqVo queryConditionsReqVo, HttpServletRequest request) {
        log.info("queryConditionsReqVo的值：{}", JSON.toJSONString(queryConditionsReqVo));
        String username = request.getHeader("username");
        log.info("username的值：{}", username);
        Result<Object> result = new Result<>();
        result.setCode(200);
        String saveName = queryConditionsReqVo.getSaveName();
        if(StrUtil.isBlank(saveName)){
            return Result.error("saveName参数不能为空");
        }
        String matchType = queryConditionsReqVo.getMatchType();
        if(StrUtil.isBlank(matchType)){
            return Result.error("matchType参数不能为空");
        }
        queryConditionsReqVo.getData().forEach(
                dataBean -> {
                    if(StrUtil.isBlank(dataBean.getFieldName())){
                        Result.error("fieldName参数不能为空");
                    }
                    if(StrUtil.isBlank(dataBean.getFileldValue())){
                        Result.error("fileldValue参数不能为空");
                    }
                    if(StrUtil.isBlank(dataBean.getRule())){
                        Result.error("rule参数不能为空");
                    }
                    String componentType = dataBean.getComponentType();
                    if (StrUtil.isBlank(componentType)){
                        result.error500("componentType参数不能为空");
                    }
                    if(StrUtil.equals(componentType,"select")){
                        List<QueryConditionsReqVo.DataBean.OptionsBean> options = dataBean.getOptions();
                        if(options == null || options.size() == 0){
                            result.error500("options参数不能为空");
                        }
                    }
                }
        );
        //先插入主表query_conditions_main
        QueryConditionsMain queryConditionsMain = new QueryConditionsMain();
        queryConditionsMain.setSaveName(saveName);
        queryConditionsMain.setMatchType(matchType);
        queryConditionsMain.setUsername(username);
        boolean save = queryConditionsMainService.save(queryConditionsMain);
        if(!save){
            return Result.error("保存失败");
        }
        log.info("主表插入成功，主键ID：{}", queryConditionsMain.getId());
        //再插入从表query_conditions_data
        queryConditionsReqVo.getData().forEach(
                dataBean -> {
                    QueryConditionsData queryConditionsData = new QueryConditionsData();
                    queryConditionsData.setMainId(queryConditionsMain.getId());
                    queryConditionsData.setFieldName(dataBean.getFieldName());
                    queryConditionsData.setFieldValue(dataBean.getFileldValue());
                    queryConditionsData.setRule(dataBean.getRule());
                    queryConditionsData.setComponentType(dataBean.getComponentType());
                    if(StrUtil.equals(dataBean.getComponentType(),"select")){
                        List<QueryConditionsReqVo.DataBean.OptionsBean> options = dataBean.getOptions();
                        queryConditionsData.setOptionss(JSON.toJSONString(options));
                    }
                    //保存从表数据
                    boolean save1 = queryConditionsDataService.save(queryConditionsData);
                    if(!save1){
                        result.error("保存失败");
                    }
                }
        );
        return result;
    }

    /**
     * 删除保存查询条件
     * @param id
     * @param request
     * @return Result<Object>
     */
    @DeleteMapping(value = "/delete")
    public Result<Object> delete(@RequestParam String id,HttpServletRequest request) {
        log.info("id的值：{}",id);
        String username = request.getHeader("username");
        log.info("username的值：{}",username);
        if(StrUtil.isBlank(username)){
            return Result.error("username的值不能为空");
        }
        //根据id和username删除
        boolean b = queryConditionsMainService.remove(Wrappers.lambdaQuery(QueryConditionsMain.class).eq(QueryConditionsMain::getUsername, username)
                .eq(QueryConditionsMain::getId, id));
        if (b){
            return Result.OK("删除成功");
        }
        return Result.error("删除失败");
    }

    @PostMapping(value = "/update")
    public ResponseEntity<Object> update(@RequestBody QueryConditionsMain params) {
        queryConditionsMainService.updateById(params);
        return new ResponseEntity<>("updated successfully", HttpStatus.OK);
    }
}
